﻿using System;
using System.Collections.Generic;
using System.Text;

namespace CommonHelper
{
    /// <summary>
    /// 36进制转化器
    /// </summary>
    public class Base36Converter
    {
        private const string Characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        // 将十进制数转换为36进制字符串
        public static string FromDecimal(long value)
        {
            if (value == 0) return "0";

            var result = new StringBuilder();
            while (value > 0)
            {
                result.Insert(0, Characters[(int)(value % 36)]);
                value /= 36;
            }
            return result.ToString();
        }

        // 将36进制字符串转换为十进制数
        public static long ToDecimal(string base36String)
        {
            if (string.IsNullOrEmpty(base36String))
                throw new ArgumentException("Input string cannot be null or empty");

            long result = 0;
            for (int i = 0; i < base36String.Length; i++)
            {
                char c = base36String[i];
                int value = Characters.IndexOf(char.ToUpper(c));

                if (value < 0)
                    throw new ArgumentException($"Invalid character '{c}' in base36 string");

                result = result * 36 + value;
            }
            return result;
        }
    }
}
